﻿/// <summary>
/// 编辑器扩展工具
/// 更新:  Bug -> GetSelectFolder 当选择文件夹时输出根目录,新设判断是否为文件夹
///		2020/5/21： 添加Func(GetAllAssets) 获取指定目录下的所有筛选资源
/// </summary>
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using UnityEngine;

	public static class EditorUtil
	{

		static public string GetSelectFolder()
		{
			string path = "Assets";
			UnityEngine.Object[] assets = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets);
			for (int index = 0; index < assets.Length; index++)
			{
				string assetPath = AssetDatabase.GetAssetPath(assets[index]);
				if (!string.IsNullOrEmpty(assetPath) && File.Exists(assetPath))
				{
					//选择为文件时
					path = Path.GetDirectoryName(assetPath);
					break;
				}
				else if (!string.IsNullOrEmpty(assetPath) && Directory.Exists(assetPath))
				{
					//选择为文件夹时
					path = assetPath;
					break;
				}
			}
			return path;
		}

		static public T GetSelect<T>() where T : UnityEngine.Object
		{
			//T ret = default;
			if (TryGetSelect(out T ret))
				return ret;
			else
				return default;
		}

		static public bool TryGetSelect<T>(out T ret) where T : UnityEngine.Object
		{
			ret = default;
			UnityEngine.Object asset = Selection.activeObject;
			string assetPath = AssetDatabase.GetAssetPath(asset);
			if (!string.IsNullOrEmpty(assetPath) && File.Exists(assetPath))
			{
				ret = asset as T;
				return true;
			}
			else
				return false;
		}

		static public void GetAllAssets<T>(string path, string filter, ref List<T> list) where T : UnityEngine.Object
		{
			//获取所有符合名称要求的资源Guid
			string[] assets = AssetDatabase.FindAssets(filter, new string[] { path, });
			foreach (var item in assets)
			{
				//检查类型是否符合要求
				T getItem = AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(item));
				if (getItem != null)
				{
					list.Add(getItem);
				}
			}
		}


		static public Component ComponentField(Component component)
		{
			var temp = component;
			Transform transform = component ? component.transform : null;
			transform = (Transform)EditorGUILayout.ObjectField(transform, typeof(Transform), true);
			if (component == null)
				temp = transform;
			else if (transform && component.transform == transform)
			{
				Component[] comps = component.GetComponents<Component>();
				string[] enumName = new string[comps.Length];
				int select = 0;
				for (int i = 0; i < comps.Length; i++)
				{
					enumName[i] = comps[i].GetType().Name;
					if (component == comps[i])
						select = i;
				}

				select = EditorGUILayout.Popup(select, enumName);
				temp = comps[select];
			}
			else
			{
				temp = transform;
			}
			return temp;
		}
	}
